var express = require('express');
var router = express.Router();
const mysql = require("../util/mysql/mysql");
//登录
router.post("/login", function (req, res, next) {
  mysql.data(
    "select * from userdata where u_user=" + req.body.u_user,
    [],
    function (err, rows, fields) {
      if (err){
        console.log(err);
        return
      }
      if (rows.length == 0) {
        res.send(JSON.stringify({ code: 0 }));
      } else if (rows[0].u_pass == req.body.u_pass) {
        res.send(JSON.stringify({ code: 1,username:rows[0].u_user,u_id:rows[0].u_id }));
      } else {
        res.send(JSON.stringify({ code: 2 }));
      }
    }
  );
});
//手机账号登录
router.post("/phone", function (req, res, next) {
  mysql.data(
    "select * from userdata where u_phone=" + req.body.u_phone,
    [],
    function (err, rows, fields) {
      if (err){
        console.log(err);
        return
      }
      if (rows.length == 0) {
        res.send(JSON.stringify({ code: 0 }));
      } else if (rows[0].u_pass == req.body.u_pass) {
        res.send(JSON.stringify({ code: 1,username:rows[0].u_user,u_id:rows[0].u_id }));
      } else {
        res.send(JSON.stringify({ code: 2 }));
      }
    }
  );
});
router.post("/adduser", function (req, res, next) {
  mysql.data(
    "select u_phone from userdata where u_phone=" + req.body.u_phone,
    [],
    function (err, rows, fields) {
      if (err){
        console.log(err);
        return
      }
      if(rows.length===0){
        mysql.data(
          "insert into userdata (u_user,u_pass,u_phone) values (?,?,?)",[
            req.body.u_phone,
            req.body.u_pass,
            req.body.u_phone,
          ],
          function (er,row,field){
            if (er){
              console.log(er);
              return
            }
            res.send(JSON.stringify({ code: 1 }));
          }
        )
      } else {
        res.send(JSON.stringify({ code: 2 }));
      }
    }
    
  );
});
module.exports = router;
